<template>
  <div id="building">
    <div class="all">
      <div class="loginBody">
        <div class="loginWindow">
          <div class="loginWindow-left">
            <div class="text">
              <!-- <img src="@/assets/images/logo2.png" alt="" /> -->
              <p>Welcome!</p>
              <p>图书商城管理平台</p>
            </div>
          </div>
          <div class="loginWindow-right">
            <div class="login">
              <table>
                <tr>
                  <td>账号</td>
                  <td>
                    <el-input maxlength="20" clearable v-model="username" style="width: 210px" placeholder="请输入账号" @input="validateInput('username')" />
                  </td>
                </tr>
                <tr>
                  <td>密码</td>
                  <td>
                    <el-input maxlength="20" v-model="password" style="width: 210px" placeholder="请输入密码" type="password"
                      show-password @input="validateInput('password')" />
                  </td>
                </tr>
              </table>
              <el-row class="loginWindow-top">
                <el-col :span="12">
                  <el-input maxlength="20" clearable v-model="codeanswer" placeholder="请输入验证码" />
                </el-col>
                <el-col :span="12">
                  <div id="aaa" @click="code()" style="cursor: pointer;"></div>
                </el-col>
              </el-row>
              <div class="login-button">
                <el-button type="success" @click="goTo(), logintime()">登录</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

const username = ref("");
const password = ref("");
const store = useStore();
const router = useRouter();
const userip = ref("");
const codeimg = ref("");
const codeanswer = ref("");
const codeanswer2 = ref("");

onMounted(() => {
  // 可以在这里执行一些初始化操作
  fetchIPAddress()
  code()
});

async function code() {
  try {
    const response = await axios.get("http://localhost:3000/api/logins/code");
    aaa.innerHTML = response.data.data;
    codeanswer2.value = response.data.text;
  } catch (error) {
    ElMessage.error('error');
  }
}

//登录验证
async function goTo() {
  try {
    if (!username.value || !password.value) {
      ElMessage.error("账号或密码不能为空");
      return;
    }
    if (!codeanswer.value) {
      ElMessage.error("请输入验证码");
      return;
    }
    if (!(codeanswer.value === codeanswer2.value ||
      codeanswer.value.toLowerCase() === codeanswer2.value.toLowerCase())) {
      ElMessage.error("验证码不正确，请重新输入");
      code();
      return;
    }
    const response = await axios.post("http://localhost:3000/api/logins/login", {
      username: username.value,
      password: password.value,
    });
    if (response.data && response.data.token) {
      const userToken = "Bearer " + response.data.token;
      await store.dispatch("updateToken", userToken);
      ElMessage.success(response.data.message);
      router.push("/index");
    } else {
      console.error("服务器响应数据格式错误");
    }
  } catch (error) {
    console.error("error", error);
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error(error.response.data.message);
      code();
    } else if (error.message) {
      ElMessage.error(error.message);
      code();
    } else {
      ElMessage.error("登录请求失败，请稍后再试");
    }
  }
}

async function logintime() {
  try {
    localStorage.removeItem("honey-admin")
    localStorage.setItem('loginTime', new Date().toLocaleString());
    const response = await axios.post(
      "http://localhost:3000/api/users/logintime/",
      { logintime: localStorage.getItem('loginTime'), username: username.value, userip: userip.value }
    );
  } catch (error) {
    console.log(error);
  }
};

async function fetchIPAddress() {
  try {
    const response = await axios.get('http://localhost:3000/api/users/loginip/');
    userip.value = response.data.loginip;
    console.log(userip);
    
  } catch (error) {
    console.error(error);
  }
}

// 添加验证函数
function validateInput(field) {
  // 只允许字母、数字和部分特殊字符（如@._-）
  const regex = /[^a-zA-Z0-9@._-]/g;
  
  if (field === 'username') {
    username.value = username.value.replace(regex, '');
    // 确保不以特殊字符开头
    username.value = username.value.replace(/^[@._-]+/, '');
  } else if (field === 'password') {
    password.value = password.value.replace(regex, '');
  }
  
  // 限制长度（可选，因为已经有maxlength属性）
  if (username.value.length > 20) {
    username.value = username.value.slice(0, 20);
  }
  if (password.value.length > 20) {
    password.value = password.value.slice(0, 20);
  }
}

</script>


<style scoped>
.all {
  font-family: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
    Oxygen, Ubuntu, Cantarell, "Fira Sans", "Droid Sans", "Helvetica Neue",
    sans-serif;
}

.loginWindow {
  background-color: transparent;
  display: flex;
  height: 400px;
  width: 1000px;
  margin: auto;
  /* text-align: center; */
  transform: translateY(60%);
  line-height: 50px;
}

.loginWindow-left {
  width: 50%;
  height: 100%;
  padding-left: 30px;
  background-image: url(@/assets/images/R-C.jpg);
  border-radius: 20px 0 0 20px;
}

.text {
  margin-top: 100px;
  transform: translateY(20%);
  font-size: 35px;
  font-weight: 600;
  color: black;
  text-align: left;
}

.text p {
  margin: 1rem;
}

.text img {
  object-fit: contain;
  height: 6.25rem;
}

.loginWindow-right {
  position: relative;
  background-color: rgb(189, 240, 247);
  width: 50%;
  height: 100%;
  border-radius: 0 20px 20px 0;
}

.login {
  position: absolute;
  top: 22%;
  left: 25%;
}

.user {
  font-size: 15px;
  height: 30px;
  width: 200px;
  padding-left: 10px;
  border: none;
  border-radius: 6px;
  background-color: #eff0ee;
}

.el-row {
  margin-top: 1rem;
  max-width: 252px;
}

.login-button {
  text-align: center;
}

.login-button button {
  /* margin: 2rem 0; */
  padding: 10px 50px;
  transition: box-shadow 0.5s;
}

.login-button button:hover {
  box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
    0 17px 50px 0 rgba(0, 0, 0, 0.19);
}
</style>
